package com.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.domain.R;
import com.store.domain.entity.Book;
import com.store.domain.entity.Collect;
import com.store.domain.vo.CollectVo;
import com.store.mapper.BookMapper;
import com.store.mapper.CollectMapper;
import com.store.service.CollectService;
import com.store.utils.BeanCopyUtils;
import com.store.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 收藏表(Collect)表服务实现类
 *
 * @author yu
 * @since 2024-06-26 01:12:42
 */
@Service("collectService")
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {


    @Resource
    private BookMapper bookMapper;
    @Override
    public R collectBook(Integer bookId) {
        Integer userId = ThreadLocalUtil.getLocal();
        Collect collect = new Collect();
        collect.setUserId(userId);
        collect.setBookId(bookId);
        boolean save = save(collect);
        if (save){
            return R.success("收藏成功");
        }
        return R.error("收藏失败");
    }

    @Override
    public R getUserCollects() {
        Integer userId = ThreadLocalUtil.getLocal();
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId,userId);
        List<Collect> collectList = list(queryWrapper);
        List<CollectVo> collectVos = BeanCopyUtils.copyBeanList(collectList, CollectVo.class);
        for (CollectVo collectVo : collectVos){
            Book book = bookMapper.selectById(collectVo.getBookId());
            collectVo.setName(book.getName());
            collectVo.setCover(book.getCover());
            collectVo.setPrice(book.getPrice());
            collectVo.setDescription(book.getDescription());
        }
        return R.success(collectVos);
    }

    @Override
    public R deleteCollects(Integer[] ids) {
        if (removeByIds(Arrays.asList(ids))){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }
}


